package com.yycx.app.provider.configuration;


import com.yycx.app.provider.integration.filter.IntegrationAuthenticationFilter;
import com.yycx.app.provider.service.impl.AppClientDetailsService;
import com.yycx.common.base.constants.FlymeConstants;
import com.yycx.common.configuration.OpenCommonProperties;
import com.yycx.common.exception.Oauth2WebResponseExceptionTranslator;
import com.yycx.common.security.OpenTokenEnhancer;
import com.yycx.common.security.TokenUtils;
import com.yycx.common.security.enums.TokenStoreEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * APP认证服务器配置
 *
 * @author zyf
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private DataSource dataSource;
    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Resource
    private ApprovalStore approvalStore;

    @Resource
    private AuthorizationCodeServices authorizationCodeServices;

    /**
     * 自定义获取客户端,为了支持自定义权限,
     */
    @Resource
    private AppClientDetailsService appClientDetailsService;

    @Autowired
    private TokenStore tokenStore;


    @Resource
    private IntegrationAuthenticationFilter integrationAuthenticationFilter;


    /**
     * TokenStore对象(可使用jdbc,jwt,redis)
     *
     * @return
     */
    @Bean
    public TokenStore tokenStore() throws Exception {
        String tokenStoreType = FlymeConstants.APP_TOKEN_STORE;
        TokenStore tokenStore = null;
        if (tokenStoreType.equals(TokenStoreEnum.REDIS.name())) {
            tokenStore = TokenUtils.buildRedisTokenStore(redisConnectionFactory);
        }
        if (tokenStoreType.equals(TokenStoreEnum.JWT.name())) {
            tokenStore = TokenUtils.buildJwtTokenStore();
        }
        if (tokenStoreType.equals(TokenStoreEnum.JDBC.name())) {
            tokenStore = TokenUtils.buildJdbcTokenStore(dataSource);
        }
        return tokenStore;
    }


    /**
     * 授权store
     *
     * @return
     */
    @Bean
    public ApprovalStore approvalStore() {
        approvalStore = new JdbcApprovalStore(dataSource);
        return approvalStore;
    }

    /**
     * 自定义令牌生成
     *
     * @return
     */
    @Bean
    TokenEnhancer tokenEnhancer() {
        return new OpenTokenEnhancer();
    }

    /**
     * 授权码store
     *
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        authorizationCodeServices = new JdbcAuthorizationCodeServices(dataSource);
        return authorizationCodeServices;
    }

    private DefaultTokenServices defaultTokenServices() throws Exception {
        String tokenStoreType = FlymeConstants.APP_TOKEN_STORE;
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(true);
        tokenServices.setClientDetailsService(appClientDetailsService);
        if (tokenStoreType.equals(TokenStoreEnum.JWT.name())) {
            tokenServices.setTokenEnhancer(TokenUtils.buildJwtTokenConverter());
            //此处只能使用tokenStore
            tokenServices.setTokenStore(tokenStore);
        }
        if (tokenStoreType.equals(TokenStoreEnum.REDIS.name()) || tokenStoreType.equals(TokenStoreEnum.JDBC.name())) {
            tokenServices.setTokenStore(tokenStore());
            tokenServices.setTokenEnhancer(tokenEnhancer());
        }
        return tokenServices;
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(appClientDetailsService);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        String tokenStoreType = FlymeConstants.APP_TOKEN_STORE;
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        endpoints.authenticationManager(authenticationManager);
        endpoints.approvalStore(approvalStore());
        if (tokenStoreType.equals(TokenStoreEnum.JDBC.name())) {
            endpoints.tokenStore(tokenStore());
        }
        endpoints.userDetailsService(userDetailsService);
        endpoints.tokenServices(defaultTokenServices());
        endpoints.authorizationCodeServices(authorizationCodeServices());
        // 自定义确认授权页面
        endpoints.pathMapping("/oauth/confirm_access", "/oauth/confirm_access");
        // 自定义错误页
        endpoints.pathMapping("/oauth/error", "/oauth/error");
        // 自定义异常转换类
        endpoints.exceptionTranslator(new Oauth2WebResponseExceptionTranslator());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 开启/oauth/token_key验证端口无权限访问
                //.tokenKeyAccess("permitAll()")
                // 开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("isAuthenticated()")
                //开启客户端授权(暂不开启,只作为用户认证中心)
                .allowFormAuthenticationForClients()
                //添加自定义登录验证
                .addTokenEndpointAuthenticationFilter(integrationAuthenticationFilter);
    }

}
